import React, { useEffect } from 'react';
import Modal from 'react-modal';

interface SimpleModalProps {
  isOpen: boolean;
  onClose: () => void;
  title: string;
  children: React.ReactNode;
}

const SimpleModal: React.FC<SimpleModalProps> = ({ isOpen, onClose, title, children }) => {
  useEffect(() => {
    // 确保在 DOM 渲染后设置 appElement
    const rootElement = document.getElementById('root');
    if (rootElement) {
      Modal.setAppElement('#root');  // 确保在根元素加载之后设置
    } else {
      console.error('No root element found for React Modal');
    }
  }, []);

  if (!isOpen) return null;

  return (
    <Modal
      isOpen={isOpen}
      onRequestClose={onClose}
      contentLabel={title}
      appElement={document.getElementById('root')!}  // 使用正确的根元素 ID
      style={{
        overlay: {
          backgroundColor: 'rgba(0, 0, 0, 0.7)', // 背景遮罩
        },
        content: {
          top: '50%', // 垂直居中
          left: '50%', // 水平居中
          right: 'auto',
          bottom: 'auto',
          marginRight: '-50%',
          transform: 'translate(-50%, -50%)', // 通过平移实现居中
          maxWidth: '500px', // 最大宽度
          width: '100%', // 宽度100%
        },
      }}
    >
      <div className="bg-white rounded-lg shadow-lg p-6">
        <h2 className="text-lg font-bold mb-4">{title}</h2>
        <div>{children}</div>
        <button onClick={onClose} className="mt-4 bg-blue-500 text-white rounded px-4 py-2">
          关闭
        </button>
      </div>
    </Modal>
  );
};

export default SimpleModal;
